﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Delay;
using System.Diagnostics;
using Microsoft.Phone.Shell;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using Microsoft.Xna.Framework.Media;
using System.IO;
using Microsoft.Phone.Tasks;
using System.Collections;

namespace PhoneInfo
{
    public partial class PivotPage1 : PhoneApplicationPage
    {
        private string topicid;
        private int    isbible=0;
        private InfoType pageType;
        private string title;//用于往数据库中存放数据
        private PhoneInfoContentView phoneInfoContent=null;
        private PhoneInfoContentView phoneInfoReply=null;
        private  int lastPage = -1;
        //private  bool bYetDownloadAll = false;
        private string urlPic="";
        public PivotPage1()
        {
            InitializeComponent();
        }
        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            //static int lastPage=-1;
            ScrollBar scrollBar = (ScrollBar)sender;
            object thumbobjet = scrollBar.GetValue(ScrollBar.SmallChangeProperty);
            object valueObj = scrollBar.GetValue(ScrollBar.ValueProperty);
            object maxObj = scrollBar.GetValue(ScrollBar.MaximumProperty);
            //scrollBar.
            if (valueObj != null && maxObj != null)
            {
                double value = (double)valueObj;
                double max = (double)maxObj - 0.5;
                Debug.WriteLine("ValueProperty si {0}", value);
                Debug.WriteLine("MaximumProperty si {0}", max);
                if(App.appSitting.AutoLoadNextPage==false)
                {
                    return;
                }
                if (value >= max)
                {
                    switch (PivotInfo.SelectedIndex)
                    {
                        case 0:
                            //
                            if (phoneInfoContent.CurrentPage * phoneInfoContent.PageSize <phoneInfoContent.TotalPage)
                            {
                                if (lastPage == phoneInfoContent.CurrentPage)                                
                                {
                                    return;
                                }

                                Debug.WriteLine("请求第{0}页面", phoneInfoContent.CurrentPage+1);
                                Debug.WriteLine("一个页面的条数{0}", phoneInfoContent.PageSize);
                                Debug.WriteLine("一共{0}条目", phoneInfoContent.TotalPage);
                                lastPage = phoneInfoContent.CurrentPage;
                                phoneInfoContent.AllowAdd = true;
                                phoneInfoContent.Result = 0;
                                ProgBar.Visibility = Visibility.Visible;
                                phoneInfoContent.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoContent.GetPhoneInfoUrl(phoneInfoContent.CurrentPage + 1, topicid, 1, pageType, isbible)));
                            }
                            break;
                        case 1:
                            //评论
                            if (phoneInfoReply.CurrentPage * phoneInfoReply.PageSize < phoneInfoReply.TotalPage)
                            {
                                //
                                if (lastPage == phoneInfoReply.CurrentPage)
                                {
                                    return;
                                }
                                lastPage = phoneInfoReply.CurrentPage;
                                phoneInfoReply.AllowAdd = true;
                                phoneInfoReply.Result = 0;
                                ProgBar.Visibility = Visibility.Visible;
                                phoneInfoReply.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoReply.GetPhoneInfoUrl(phoneInfoReply.CurrentPage + 1, topicid, 1, pageType, isbible)));
                            }
                            break;
                    }
                  
                   
                  
                }
            }
        }
        public static List<T> GetVisualChildCollection<T>(object parent) where T : UIElement
        {
            List<T> visualCollection = new List<T>();
            GetVisualChildCollection(parent as DependencyObject, visualCollection);
            return visualCollection;
        }
        private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : UIElement
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {
                    visualCollection.Add(child as T);
                }
                else if (child != null)
                {
                    GetVisualChildCollection(child, visualCollection);
                }
            }
        }
        private void FirstListBox_Loaded(object sender, RoutedEventArgs e)
        {
        
                List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(sender);
                foreach (ScrollBar scrollBar in scrollBarList)
                {
                    if (scrollBar.Orientation == System.Windows.Controls.Orientation.Horizontal)
                    {

                    }
                    else
                    {
                        scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(verticalScrollBar_ValueChanged);
                    }
                }
            //}
            
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //bYetDownloadAll = false;
            lastPage = -1;
            IDictionary<string, string> parameters = this.NavigationContext.QueryString;
            if (parameters.ContainsKey("topicid"))
            {
                topicid = parameters["topicid"];
            }
            if (parameters.ContainsKey("readcount"))
            {
                readCount.Text = parameters["readcount"];
            }
            if (parameters.ContainsKey("replycount"))
            {
                replyCount.Text = parameters["replycount"];
            }
            if (parameters.ContainsKey("ShrewdEye"))
            {
                pageType = InfoType.Eye;//精明眼

            }
            if (parameters.ContainsKey("title"))
            {
                title = parameters["title"];

            }
            else 
            {
                pageType = InfoType.Info;//资讯列表
            }
            if (parameters.ContainsKey("IsBible"))
            {
                isbible = Convert.ToInt32(parameters["IsBible"]);
            }
            
            if (PivotInfo.SelectedIndex==1)
            {
                if (phoneInfoReply != null)
                {
                    try
                    {
                        MoreListBox.SelectedIndex = 0;
                        MoreListBox.ScrollIntoView(MoreListBox.SelectedItem);
                    }
                    catch(Exception)
                    {

                    }
                    
                    phoneInfoReply = new PhoneInfoContentView();
                    phoneInfoReply.ClassNmae = "phoneInfoReply";
                    phoneInfoReply.AllowAdd = false;
                    phoneInfoReply.CurrentPage = 1;
                  
                    phoneInfoReply.PageSize = 20;
                    phoneInfoReply.Result = 0;
                    ProgBar.Visibility = Visibility.Visible;
                    phoneInfoReply.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(InfoContent_PropertyChanged);
                    phoneInfoReply.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoReply.GetPhoneInfoUrl(phoneInfoContent.CurrentPage, topicid, 1, pageType, isbible)));
                    pivotReply.DataContext = null;//设置数据绑定

                }

              
            }
            phoneInfoContent = new PhoneInfoContentView();
            phoneInfoContent.ClassNmae = "phoneInfoContent";
            phoneInfoContent.AllowAdd = false;
            phoneInfoContent.CurrentPage = 1;
          
            phoneInfoContent.TotalPage = 0;
           // if ( App.netType == NetWorkTypes.WiFi)
           //{
           //    phoneInfoContent.PageSize = 100;
           // }
           // else
           // {
                phoneInfoContent.PageSize = 6;
           // }
           
            ProgBar.Visibility = Visibility.Visible;
            phoneContent.DataContext = phoneInfoContent;//第一个pivot控件的的数据绑定
            phoneInfoContent.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(InfoContent_PropertyChanged);
            phoneInfoContent.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoContent.GetPhoneInfoUrl(phoneInfoContent.CurrentPage, topicid, 1, pageType, isbible)));   
            //
            //if (bYetDownloadAll == false)
            //{
            //    bYetDownloadAll = true;
            //    if (App.netType == NetWorkTypes.WiFi)
            //    {
            //        phoneInfoContent.TotalPage = 0;
            //        phoneInfoContent.PageSize = 100;
            //        phoneInfoContent.AllowAdd = false;
            //        phoneInfoContent.Result = 0;
            //        // ProgBar.Visibility = Visibility.Visible;
            //        phoneInfoContent.SetValue(LowProfileXmlLoader.UriSourceProperty,
            //                                new Uri(phoneInfoContent.GetPhoneInfoUrl(
            //                                    1, topicid, 1,
            //                                    pageType, isbible)));
            //    }
            //}
                                
        }
        void InfoContent_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender == null)
                return;
            PhoneInfoContentView se = sender as PhoneInfoContentView;
            if (se == null)
                return;
            if (e.PropertyName == "Result")
            {
                switch (se.Result)
                {
                    case -1:
                    case 1:
                        if (se.ClassNmae == "phoneInfoReply")
                        {
                            titleText.Visibility = Visibility.Visible;
                          
                        }
                        else
                        {
                            ToastPrompt toast = new ToastPrompt()
                            {
                                Message="获取内容信息失败，请稍后再试！"
                            };
                            toast.Show();
                        }                      
                        ProgBar.Visibility = Visibility.Collapsed;
                        break;
                    case 2:
                        if (se.ClassNmae == "phoneInfoReply")
                        {
                            titleText.Visibility = Visibility.Collapsed;
                            ProgBar.Visibility = Visibility.Collapsed;
                            pivotReply.DataContext = se;
                            replyCount.Text = se.ReplyCount;
                            
                            
                        }
                        else
                        {
                            ProgBar.Visibility = Visibility.Collapsed;
                            readCount.Text = se.ReadCount;
                            replyCount.Text = se.ReplyCount;
                            phoneContent.DataContext = se;
                            if (se.CurrentPage == 1)
                            {
                               
                            }
                        }
                        break;
                }
            }

        }
        private void FullModePopup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FullModePopup.IsOpen = false;
        }
        private void FirstListBox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Debug.WriteLine("Tap");
            if ((PhoneInfoCenterItem)((ListBox)sender).SelectedItem == null && ((ListBox)sender).SelectedIndex == -1)
            {
                return;

            }
            Debug.WriteLine("Tap1");
            urlPic = "";
            PhoneInfoCenterItem item=(PhoneInfoCenterItem)((ListBox)sender).SelectedItem;
            string url = item.Keywords;
            if (url != null && (url.IndexOf("http")>=0))
            {
                
                if (FullModePopup != null)
                {
                    urlPic = url;
                    popImage.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(url));
                    FullModePopup.IsOpen = true;
                    if (App.appSitting.Theme == 1)
                    {
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSavePic"];
                    }
                    else
                    {
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSavePic1"];
                    }
                   // ApplicationBar = (ApplicationBar)this.Resources[""];
                }
                return;
            }
            else if (item.Type == "Tail")
            {
                string objective = "/Page/ContentAndReply.xaml";
                if (item.Topicid == null)
                {
                    MessageBox.Show("该帖子ID有错误，请刷新后重试！");
                    return;
                    
                }
                else
                {
                    if (item.Title.IndexOf("销售商家") >= 0 || item.Title.IndexOf("联系电话") >= 0 || item.Title.IndexOf("联系QQ") >= 0)
                    {
                        //PhoneCallTask task = new PhoneCallTask();
                        //task.PhoneNumber = parameters[0];
                        //task.DisplayName = parameters[1];
                        if (item.Title.IndexOf("联系电话") > 0)
                        {
                            PhoneCallTask task = new PhoneCallTask();
                            task.PhoneNumber = item.Topicid;
                            task.Show();
                            //task.DisplayName = parameters[1];
                        }
                        else
                        {
                          
                     
                            WebBrowserTask webBrowserTask = new WebBrowserTask();
                            webBrowserTask.Uri = new Uri(item.Topicid, UriKind.Absolute);
                            webBrowserTask.Show();
                           
                        }
                    }
                    else
                    {
                        objective += "?topicid=" + item.Topicid;
                        objective += "&title=" + item.Title;
                        NavigationService.Navigate(new Uri(objective, UriKind.Relative));
                    }
             
                }
               

            }
            else if (item.Type == "LastTitle")
            {
                if(App.appSitting.AutoLoadNextPage==false)
                {
                    switch (PivotInfo.SelectedIndex)
                    {
                        case 0:
                            //
                            if (phoneInfoContent.CurrentPage * phoneInfoContent.PageSize <= phoneInfoContent.TotalPage)
                            {
                                if (lastPage == phoneInfoContent.CurrentPage)
                                {
                                    return;
                                }
                                lastPage = phoneInfoContent.CurrentPage;
                                phoneInfoContent.AllowAdd = true;
                                phoneInfoContent.Result = 0;
                                ProgBar.Visibility = Visibility.Visible;
                                phoneInfoContent.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoContent.GetPhoneInfoUrl(phoneInfoContent.CurrentPage + 1, topicid, 1, pageType, isbible)));
                            }
                            break;
                        case 1:
                            //评论
                            if (phoneInfoReply.CurrentPage * phoneInfoReply.PageSize <= phoneInfoReply.TotalPage)
                            {
                                //
                                if (lastPage == phoneInfoReply.CurrentPage)
                                {
                                    return;
                                }
                                lastPage = phoneInfoReply.CurrentPage;
                                phoneInfoReply.AllowAdd = true;
                                phoneInfoReply.Result = 0;
                                ProgBar.Visibility = Visibility.Visible;
                                phoneInfoReply.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoReply.GetPhoneInfoUrl(phoneInfoReply.CurrentPage + 1, topicid, 1, pageType, isbible)));
                            }
                            break;
                    }
                }
            }
        }
        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null)
                return;
            lastPage = -1;
            FullModePopup.IsOpen = false;
            switch (((Pivot)sender).SelectedIndex)
            {
                case 0:
                    //内容
                    if (App.appSitting.Theme == 1)
                    {
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarContent"];
                    }
                    else
                    {
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarContent1"];
                    }
                   // ApplicationBar = ((ApplicationBar)this.Resources[""]);
                    break;
                case 1:
                    //评论
                    {
                        if (App.appSitting.Theme == 1)
                        {
                            ApplicationBar = (ApplicationBar)this.Resources["AppBar"];
                        }
                        else
                        {
                            ApplicationBar = (ApplicationBar)this.Resources["AppBar1"];
                        }
                        //ApplicationBar = ((ApplicationBar)this.Resources[""]);
                        if (phoneInfoReply == null)
                        {
                            phoneInfoReply = new PhoneInfoContentView();

                            phoneInfoReply.ClassNmae = "phoneInfoReply";
                            phoneInfoReply.AllowAdd = false;
                            phoneInfoReply.CurrentPage = 1;
                            phoneInfoReply.PageSize = 20;
                            phoneInfoReply.Result = 0;
                            ProgBar.Visibility = Visibility.Visible;
                            phoneInfoReply.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(InfoContent_PropertyChanged);
                            phoneInfoReply.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoReply.GetPhoneInfoUrl(phoneInfoContent.CurrentPage, topicid, 1, pageType, isbible)));
                            pivotReply.DataContext = phoneInfoReply;//设置数据绑定

                        }

                    }
                    break;
            }
            //
        }
        private void Reply(object sender, EventArgs e)
        {//发表评论
          //
            if (sender==null)
            {
                return;
                //容错的情况
            }
            
            string objective = "/Page/Comment.xaml";
            objective += "?topicid=" + topicid;
            if (InfoType.Eye == pageType)
            {
               // pageType = InfoType.Eye;//精明眼
                objective += "&ShrewdEye=" + "ShrewdEye";
            }
           
            NavigationService.Navigate(new Uri(objective, UriKind.Relative)); 
        }
        private void refresh(object sender, EventArgs e)
        {//刷新
            if (PivotInfo.SelectedIndex == 0)
            {
                if (phoneInfoContent != null)
                {
                   
                    phoneInfoContent = new PhoneInfoContentView();
                    phoneInfoContent.ClassNmae = "phoneInfoContent";
                    phoneInfoContent.AllowAdd = false;
                    phoneInfoContent.CurrentPage = 1;
                    //phoneInfoReply.Count = parameters["readcount"];
                    phoneInfoContent.TotalPage = 0;
                    phoneInfoContent.PageSize = 3;
                    ProgBar.Visibility = Visibility.Visible;
                    phoneContent.DataContext = null;//第一个pivot控件的的数据绑定
                    phoneInfoContent.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(InfoContent_PropertyChanged);
                    phoneInfoContent.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoContent.GetPhoneInfoUrl(phoneInfoContent.CurrentPage, topicid, 1, pageType, isbible)));

                }
            }
            else if (PivotInfo.SelectedIndex == 1)
            {
                if (phoneInfoReply != null)
                {
                    try
                    {
                        MoreListBox.SelectedIndex = 0;
                        MoreListBox.ScrollIntoView(MoreListBox.SelectedItem);
                    }
                    catch(Exception)
                    {

                    }
                    phoneInfoReply = new PhoneInfoContentView();

                    phoneInfoReply.ClassNmae = "phoneInfoReply";
                    phoneInfoReply.AllowAdd = false;
                    phoneInfoReply.CurrentPage = 1;
                    phoneInfoReply.PageSize = 20;
                    phoneInfoReply.Result = 0;
                    ProgBar.Visibility = Visibility.Visible;
                    phoneInfoReply.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(InfoContent_PropertyChanged);
                    phoneInfoReply.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(phoneInfoReply.GetPhoneInfoUrl(phoneInfoContent.CurrentPage, topicid, 1, pageType, isbible)));
                    pivotReply.DataContext = null;//设置数据绑定
                   
                }
            }
        }
        private void Shard(object sender, EventArgs e)
        {
            if (sender==null)
            {
                return;
            }
            CollectTable collectItem = new CollectTable()
            {
                Readcount = readCount.Text ,
                Replycount = replyCount.Text,
                Topicid =topicid,
                Title = title
            };
            writeSoftwareSittingForDB(collectItem);
        }
        private void writeSoftwareSittingForDB(CollectTable collectItem)
        {
            //此函数只在数据库为空时调用
            //如果数据库中该表不为空 则返回
            var CollectInDB = from CollectTable item in App.ManagerDB.collectTable
                              select item;
            foreach (var item in CollectInDB)
            {
                if (item.Topicid == collectItem.Topicid)
                {
                    ToastPrompt toastPrompt = new ToastPrompt()
                    {
                        Message = "已经收藏过这条信息"
                    };
                    toastPrompt.Show();
                    return;
                }
               
            }
            CollectTable softSitting = new CollectTable()
            {
                Readcount = collectItem.Readcount,
                Replycount = collectItem.Replycount,
                Topicid = topicid,
                Title =title
            };
            // 
            try
            {
                App.ManagerDB.collectTable.InsertOnSubmit(softSitting);
                App.ManagerDB.SubmitChanges();
                ToastPrompt toastPrompt = new ToastPrompt()
                {
                    Message = "收藏成功！"
                };
                toastPrompt.Show();
            }
            catch(Exception e)
            {
                Debug.WriteLine("Exception message is {0}", e.Message);
                Debug.WriteLine("Exception data is {0}", e.Data);
                ToastPrompt toastPrompt = new ToastPrompt()
                {
                    Message = "收藏失败，请重试"
                };
                toastPrompt.Show();
            }
            
        }
        private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            e.Handled = true;
            //
            //将它保存到相册
        
            return;
        }
        private void Grid_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
           //将它保存到相册
            FullModePopup.IsOpen = false;
            if (App.appSitting.Theme == 1)
            {
                ApplicationBar = (ApplicationBar)this.Resources["AppBarContent"];
            }
            else
            {
                ApplicationBar = (ApplicationBar)this.Resources["AppBarContent1"];
            }
            //ApplicationBar = (ApplicationBar)this.Resources[""];
          //
        }
        private void save(object sender, EventArgs e)
        {

            using (Stream stream = LowProfileXmlLoader.LoadCachedImage(new Uri(urlPic)))
            {
                if (stream == null)
                {
                    ToastPrompt toast = new ToastPrompt()
                    {
                        Message = "读取图片失败！"
                    };
                    return;
                }
                else
                {
                     MediaLibrary mediaLibrary = new MediaLibrary();
                    int end=urlPic.LastIndexOf(".");
                    if(end<0)
                    {
                         ToastPrompt toast = new ToastPrompt()
                        {
                            Message = "图片格式有错误！"
                        };
                       return;
                    }
                     string endfilename = urlPic.Substring(end);
                     string tempUmd = MD5.GetMd5String(LowProfileXmlLoader.GetParsePath(urlPic));
                     string fileName = tempUmd + endfilename;
                     Picture pic = mediaLibrary.SavePicture(fileName, stream);
                   //  PhotoChooserTask photoChooserTask = new PhotoChooserTask();
                    // photoChooserTask.Show();
                     //ToastPrompt toast1 = new ToastPrompt()
                     //{
                     //    Message="图片保存成功"
                     //};
                     //toast1.Show();
                     MessageBox.Show("图片保存成功");
                }
            }
           //
        
         }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {

            if (FullModePopup.IsOpen == true)
            {
                FullModePopup.IsOpen = false;
                if (App.appSitting.Theme == 1)
                {
                    ApplicationBar = (ApplicationBar)this.Resources["AppBarContent"];
                }
                else
                {
                    ApplicationBar = (ApplicationBar)this.Resources["AppBarContent1"];
                }
                //ApplicationBar = (ApplicationBar)this.Resources[""];
                e.Cancel = true;
            }
            else
            {
                base.OnBackKeyPress(e);
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            //取消
            FullModePopup.IsOpen = false;
            if (App.appSitting.Theme == 1)
            {
                ApplicationBar = (ApplicationBar)this.Resources["AppBarContent"];
            }
            else
            {
                ApplicationBar = (ApplicationBar)this.Resources["AppBarContent1"];
            }
            //ApplicationBar = (ApplicationBar)this.Resources[""];
        }
        private void setting(object sender, EventArgs e)
        {
            //
            string page = "/Page/SoftSiting.xaml";
            NavigationService.Navigate(new Uri(page, UriKind.Relative));

        }
        private void messageBoard(object sender, EventArgs e)
        {
            string page = "/Page/MessageBoard.xaml";
            NavigationService.Navigate(new Uri(page, UriKind.Relative));
        }
        private void about(object sender, EventArgs e)
        {
            string page = "/Page/About.xaml";
            NavigationService.Navigate(new Uri(page, UriKind.Relative));
        }

        static T FindChildOfType<T>(DependencyObject root) where T : class
        {
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild != null)
                    {
                        return typedChild;
                    }
                    queue.Enqueue(child);
                }
            }
            return null;
        }
        VisualStateGroup FindVisualState(FrameworkElement element, string name)
        {
            if (element == null)
            {
                return null;
            }
            IList groups = VisualStateManager.GetVisualStateGroups(element);
            foreach (VisualStateGroup group in groups)
            {
                if (group.Name == name)
                    return group;
            }
            return null;
        }
      

        

    }

}
